﻿using GlennQuigmire.API.Application.GDtos;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace GlennQuigmire.API.Application.Commands
{
    public class MaterialParentIdSearchHander : IRequestHandler<MaterialParentIdSearchCommand, ResultT<MaterialParentIdsDto>>
    {


        private readonly IBaseRepositorys<Product> productRepository;
        private readonly IBaseRepositorys<Material> materialRepository;

        public MaterialParentIdSearchHander(IBaseRepositorys<Product> productRepository, IBaseRepositorys<Material> materialRepository)
        {
            this.productRepository = productRepository;
            this.materialRepository = materialRepository;
        }
        /// <summary>
        /// 获取物料产品信息
        /// </summary>
        /// <param name="request">获取产品请求对象</param>
        /// <param name="cancellationToken">允许异步</param>
        /// <returns>返回物料产品响应对象</returns>
        public async Task<ResultT<MaterialParentIdsDto>> Handle(MaterialParentIdSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ResultT<MaterialParentIdsDto>();

                var list1 = (from a in materialRepository.GetAll().Where(x => !x.DeleteDate && x.ParentId == 0)
                             join b in productRepository.GetAll() on a.ProductId equals b.ProductId
                             select new MaterialParentIdsDto()
                             {
                                 MaterialId = a.MaterialId,
                                 ProductName = b.ProductName,
                                 ParentName = ""
                             }).ToList();
                result.Data =  list1.Distinct().ToList();

                var list = (from a in materialRepository.GetAll().Where(x =>  !x.DeleteDate)
                            join b in productRepository.GetAll() on a.ProductId equals b.ProductId
                            join c in productRepository.GetAll() on a.ParentId equals c.ProductId
                            select new MaterialParentIdsDto()
                            {
                                MaterialId = a.MaterialId,
                                ProductName = b.ProductName,
                                ParentName = c.ProductName
                            }).Distinct().ToList();
                result.Data.AddRange(list);
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

       

    }
}
